package com.aida.evil.eda.Answer;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.SystemData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.MyView.CircleImageView;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.github.johnpersano.supertoasts.SuperToast;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


/****************************************************
 * com.aida.evil.eda.Answer.AnswerResult
 * 作者：白雨濃  evil
 * 时间：16-2-20 12:19
 * 邮箱：evilbai@foxmail.com
 * 页面用途：提示答题完成的结果
 ****************************************************/
public class AnswerResult extends AppCompatActivity
{
    private static final String INTEGRALURL = "http://" + NetworkData.ServiceIP + "/UserIntegral?";//积分上传url

    private static final int[] img_bads = {R.mipmap.bad_1, R.mipmap.bad_2, R.mipmap.bad_3};
    private static final int[] img_goods = {R.mipmap.good_1, R.mipmap.good_2, R.mipmap.good_3};

    private ViewStub viewstub;
    private LinearLayout linearLayout;
    private ProgressBar progressBar;

    private ImageView img;/*展示的图片*/
    private TextView in1_TextView;/*原始流量*/
    private TextView in2_TextView;/*添加的流量*/
    private TextView in3_TextView;/*现在的流量*/


    private CircleImageView userImg_ImageView;/*用户头像*/
    private TextView userPhoneNum_TextView;/*用户手机号*/
    private TextView userName_TextView;/*用户名*/
    private TextView date_TextView;/*日期*/
    private TextView yes_TextView;/*正确个数*/
    private TextView no_TextView;/*错误个数*/

    private ImageButton shareBackButton;
    private ImageButton goBackButton;


    private String flowSum_AES;/*流量（加密）*/
    private String flowSum;/*网络返回的 加成流量*/
    private String originalFlow;/*原始的流量*/
    private int yes_num;/*正确个数*/
    private int size;/*题目总数*/


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.answerresult);
        initView();/*初始化控件1*/
        getIntentData();/*获取正确错误个数*/
        toNetWork();/*网络加载，获取流量信息*/
        onClick();/*底部按钮点击监听*/
    }

    /**
     * 初始化控件
     */
    private void initView()
    {
        viewstub = (ViewStub) findViewById(R.id.answerResult_viewstub);
        linearLayout = (LinearLayout) findViewById(R.id.answerResult_linearLayout);
        progressBar = (ProgressBar) findViewById(R.id.answerResult_progressBar);
        img = (ImageView) findViewById(R.id.answerResult_img);
        in1_TextView = (TextView) findViewById(R.id.answerResult_in1);
        in2_TextView = (TextView) findViewById(R.id.answerResult_in2);
        in3_TextView = (TextView) findViewById(R.id.answerResult_in3);


        shareBackButton = (ImageButton) findViewById(R.id.answerResult_shareBackButton);
        goBackButton = (ImageButton) findViewById(R.id.answerResult_goBackButton);
    }

    /**
     * 动态加载布局第二次初始化
     */
    private void initView2()
    {
        userImg_ImageView = (CircleImageView) findViewById(R.id.answerResult_userImg);
        userPhoneNum_TextView = (TextView) findViewById(R.id.answerResult_userPhoneNum);
        userName_TextView = (TextView) findViewById(R.id.answerResult_userName);
        date_TextView = (TextView) findViewById(R.id.answerResult_date);
        yes_TextView = (TextView) findViewById(R.id.answerResult_yes);
        no_TextView = (TextView) findViewById(R.id.answerResult_no);
    }

    /**
     * 设置数据
     */
    private void initData()
    {
        {/*设置用户头像*/
            Picasso.with(this).load(R.mipmap.eda).into(userImg_ImageView);
        }
        {/*设置用户信息*/
            if (UserData.DATA_PHONENUM.equals("") || UserData.DATA_PHONENUM == null)
                userPhoneNum_TextView.setText("手机号：未设置");
            else
                userPhoneNum_TextView.setText("手机号：" + UserData.DATA_PHONENUM);

            if (UserData.DATA_USERNAME.equals("") || UserData.DATA_USERNAME == null)
                userName_TextView.setText("用户名：未设置");
            else
                userName_TextView.setText("用户名：" + UserData.DATA_USERNAME);
        }
        {/*设置日期，正确，错误*/
            date_TextView.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            yes_TextView.setText("正确：" + yes_num);
            no_TextView.setText("错误：" + (size - yes_num));
        }
        {/*底部展示图片*/
            bottomImg();/*随机加载，并且闪光震动*/
        }
        {/*原始流量，加成流量，现在流量*/
            in1_TextView.setText("原累计流量：" + isEmptytoInt(originalFlow));
            in2_TextView.setText("本次获得流量：" + isEmptytoInt(flowSum));
            in3_TextView.setText("总流量：" + (isEmptytoInt(originalFlow) + isEmptytoInt(flowSum)));
        }
        {/*返回首页按钮*/
            Picasso.with(this).load(R.mipmap.icn_1).into(goBackButton);
            Picasso.with(this).load(R.mipmap.icn_3).into(shareBackButton);
        }
    }

    private int isEmptytoInt(String s)
    {
        if (s != null)
            if (!s.equals(""))
                return Integer.valueOf(s);
        return 0;
    }

    /**
     * 底部图片，闪光震动
     */
    private void bottomImg()
    {
        int random = new Random().nextInt(3);
        if (yes_num >= size - yes_num)
            Picasso.with(this).load(img_goods[random]).into(img);
        else
            Picasso.with(this).load(img_bads[random]).into(img);
    }

    /**
     * 得到流量数据
     */
    private void getIntentData()
    {
        flowSum_AES = getIntent().getStringExtra("flowSum");
        yes_num = getIntent().getIntExtra("yes", 0);
        size = getIntent().getIntExtra("size", 0);
    }

    /**
     * 分步加载布局
     */
    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            if (viewstub != null)
            {
                viewstub.inflate();
                initView2();
                initData();
            }
        }
    };

    /**
     * 上传流量，更新用户积分，通过AES两次加密
     */
    private void toNetWork()
    {
        progressBar.setVisibility(View.VISIBLE);
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            @Override
            public void reqSuccess(String response)
            {
                progressBar.setVisibility(View.GONE);
                linearLayout.setVisibility(View.VISIBLE);
                handler.sendEmptyMessage(0);
                String[] ss = response.split(">-<");
                originalFlow = ss[0];
                flowSum = ss[1];
            }

            @Override
            public void reqError(String error)
            {
                progressBar.setVisibility(View.INVISIBLE);

                CustomSuperActivityToast.makeText(AnswerResult.this,
                        "网络错误，请重试", "重试", new SuperToast.OnClickListener()
                        {
                            @Override
                            public void onClick(View view, Parcelable token)
                            {
                                toNetWork();
                            }
                        }).show();
            }
        };
        Map<String, String> map = new HashMap<>();
        map.put("userPhoneNum", UserData.DATA_PHONENUM);
        map.put("flowSum", flowSum_AES);
        //map.put("flowSum", "Ymy//bPBrOrk2oGmbT5tIaWMFKqCTIhiN5XOso9UyIY=");
        VolleyHttpRequest.String_request(INTEGRALURL, map, stringVolleyHandler);
    }

    /**
     * 底部按钮点击监听
     */
    private void onClick()
    {
        goBackButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                finish();
            }
        });
        shareBackButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                showShare();
            }
        });
    }


    /**
     * 分享
     */
    private void showShare()
    {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本，啦啦啦~");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片

        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");
        // 启动分享GUI
        oks.show(this);
    }


    //-----------------------------------------------------------------------------
    @Override
    public void onBackPressed()
    {
        finish();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        ShareSDK.stopSDK(this);
    }
}
